package com.cskaoyan.mall.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName FileUploadUtils
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2022/3/7 10:11
 * @Version V1.0
 **/
public class FileUploadUtils {

    public static Map<String, String> parseRequest(HttpServletRequest request){
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //下面三行代码的作用是设置一个临时的缓存仓库，用来进行大文件上传时使用
        ServletContext servletContext = request.getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);
        Map<String, String> params = new HashMap<>();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        // bytes----
//        upload.setFileSizeMax(1024);
        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                //里面有一个方法， 可以判断当前item是否时普通的表单数据
                if(item.isFormField()){
                    processFordField(item, params);
                }else {
                    processUploadFile(item, params, request);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        return params;
    }

    private static void processUploadFile(FileItem item, Map<String, String> params, HttpServletRequest request) {
        String fieldName = item.getFieldName();
        String fileName = item.getName();
        String uuid = UUID.randomUUID().toString();
        fileName = uuid + "-" + fileName;
        int hashCode = fileName.hashCode();
        String hexString = Integer.toHexString(hashCode);
        char[] chars = hexString.toCharArray();
        String basePath = "/static/image";
        for (char aChar : chars) {
            basePath = basePath + "/" + aChar;
        }
        String relativePath = basePath + "/" + fileName;
        String realPath = request.getServletContext().getRealPath(relativePath);
        File file = new File(realPath);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try {
            item.write(file);
            params.put(fieldName, relativePath);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void processFordField(FileItem item, Map<String, String> params) {
        String name = item.getFieldName();
        String value = null;
        try {
            value = item.getString("utf-8");
            params.put(name, value);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
